package cn.dapeng.common.nio;


import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class ZeroCopy {

    public static void main(String[] args) throws Exception {
        mmapOperator("d:\\mmap\\xxx", "contentxxxx");
    }

    public static void mmapOperator(String fileName, String content) {
        File file = new File(fileName);

        try (FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel()) {
            MappedByteBuffer mmap = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 3 * 1024 * 1024);

            //把文件写入内存
            mmap.put(content.getBytes());
            // 刷盘  数据从内存 同步到磁盘
            mmap.flip();

            byte[] bb = new byte[8];
            mmap.get(bb, 0, 8); //数据读取
            System.out.println(new String(bb));
        } catch (Exception e) {

        }
    }

}
